from machine import PWM,Pin
import socket
import network
import camera
import _thread
import time
import sys


#连接热点
def do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('meik30s', '5201314ygyu')  #配置热点名称和密码
        i = 1
        while not wlan.isconnected():
            print("正在链接...{}".format(i))
            i += 1
            time.sleep(1)
    print('network config:', wlan.ifconfig())
    
do_connect()

#用于蜂鸣器的警报发声
def buzzer_sound(alerts):
    # 处理接收的数据,开启蜂鸣器警报
    buzzer = PWM(Pin(25))  #定义蜂鸣器管脚
    buzzer.duty(0) #初始化蜂鸣器
    
    if alerts == "1":
        #print("蜂鸣器响!!")
        buzzer.freq(3234)
        buzzer.duty(250)
        
    else:
        #print("蜂鸣器不响!!")
        buzzer.duty(0)
        

#接受指令的TCP子线程
def accept_tcp_test(*args, **cahe):
    # 创建TCP套接字,用于接受指令
    server_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定本地信息
    server_s.bind(("", 7788))
    # 设置为被动的
    server_s.listen(128)
    # 等待客户端链接
    new_s, client_info = server_s.accept()
    
    while True:
        print(1)
       
        recv_content = new_s.recv(1024)
        com_value =recv_content.decode('utf-8')

        if not recv_content:
            # 当客户端调用了close后，recv返回值为空，此时服务套接字就可以close了
            # 关闭服务套接字
            new_s.close()
            buzzer_sound(com_value)
            break

        # 关闭监听套接字
        server_s.close()
        
        time.sleep(1)

def accept_udp_test(server_s):
    server_s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_s.bind(("", 7788))
    while True:
        recv_content = server_s.recvfrom(1024)
        com_value =recv_content.decode('utf-8')
        if not recv_content:
            # 当客户端调用了close后，recv返回值为空，此时服务套接字就可以close了
            # 关闭服务套接字
            new_s.close()
            buzzer_sound(com_value)
            break

        # 关闭监听套接字
        server_s.close()
        
        time.sleep(10)
        

# 摄像头初始化
try:
   camera.init(0, format=camera.JPEG)
except Exception as e:
    camera.deinit()
    camera.init(0, format=camera.JPEG)
    
# 上翻下翻
camera.flip(0)
#左/右
camera.mirror(1)
# 分辨率
camera.framesize(camera.FRAME_HVGA)
# 特效
camera.speffect(camera.EFFECT_NONE)
# 白平衡
camera.whitebalance(camera.WB_HOME)
# 饱和
camera.saturation(0)
# 亮度
camera.brightness(0)
# 对比度
camera.contrast(0)
# 质量
camera.quality(10)
# socket UDP 的创建

# socket tcp 的创建
#s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)

def wireless_video_transfer():
    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,0)
    accept_udp_test(s)
    
    try:
        while True:
            buf = camera.capture()  # 获取图像数据
            s.sendto(buf, ("192.168.244.56", 9090))  # udp向服务器发送图像数据,注意连接手机热点，会导致ESP32与电脑IP一直变化
            #s.send(buf, ("192.168.84.56", 9090))
            #thread_1 = _thread.start_new_thread(accept_tcp_test, (1,))
            
    except:
        pass
    finally:
        camera.deinit()
    time.sleep(0.1)


# 这里创建接受指令
thread_1 = _thread.start_new_thread(accept_udp_test, (1,))


#用于传送视频数据
while True:
    wireless_video_transfer()
    
    

    
